// 补位，添加占位符0
const restock = (num, len = 2) => {
	num = String(num)
	len = Number(len)
	let textAr = num.split()
	for (let i = 0; i < len - num.length; i++) {
		textAr.unshift('0')
	}
	return textAr.join("")
}

// 时间格式化为 yyyy-mm-dd, 可自定义year，month，day
// YY-MM-DD
const timeFormatYMD = (time, year = 0, month = 1, day = 0) => {
	const date = new Date(time)
	date.setDate(date.getDate() + day)
	date.setMonth(date.getMonth() + (month - 1))
	date.setFullYear(date.getFullYear() + year)

	const y = date.getFullYear() // 可返回一个表示年份的 4 位数字
	const m = restock(date.getMonth() + 1) // 可返回表示月份的数字。返回值是 0（一月） 到 11（十二月） 之间的一个整数 // 注意： 一月为 0, 二月为 1, 以此类推。
	const d = restock(date.getDate())

	return y + '-' + m + '-' + d
}

// HH-MM-SS
const timeFormatHMS = (time, haveHour = true) => {
	const date = new Date(time)
	const h = date.getHours()
	const m = date.getMinutes()
	const s = date.getSeconds()
	let text = restock(m) + ":" + restock(s)
	if (haveHour) {
		text.unshift(restock(h) + ":")
	}
	return text
}

// 倒计时
const timeCountdown = (setTime, callback, haveHour = true) => {
	let time = setTime
	let timeSet = setInterval(() => {
		if (time > 0) {
			time--;
			callback(true, timeFormatHMS(time * 1000, haveHour))
		} else {
			callback(false, timeFormatHMS(time * 1000, haveHour))
			clearInterval(timeSet)
			timeSet = null
		}

	}, 1000);
}

const searchTimeChange = (timeType) => {
	let startTime = new Date("2023-11-30").getTime()
	let endTime = new Date("2024-02-31").getTime()
	if (timeType == "start") {
		let nextTwoMonth = new Date(timeFormatYMD(startTime, 0, 3)).getTime()
		return timeFormatYMD(endTime <= nextTwoMonth ? startTime >= endTime ? startTime : endTime :
			nextTwoMonth)
	} else {
		let preTwoMonth = new Date(timeFormatYMD(endTime, 0, -1)).getTime()
		return timeFormatYMD(startTime >= preTwoMonth ? startTime >= endTime ? endTime : startTime :
			preTwoMonth)
	}
}